package com.cm.sys.framework.application;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cm.sys.framework.execption.BusinessException;

/***
 * 自定义返回参数
 * 
 * @author yuqiang
 * @date 2019/07/25
 */
@Service
public class ReponseReturnHandler implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.getParameterType() == ResponseResult.class;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest) throws Exception {
        // 标识请求是否已经在该方法内完成处理
        mavContainer.setRequestHandled(true);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            ResponseResult rr;
            if (returnValue == null) {
                rr = new ResponseResult();
            } else {
                rr = (ResponseResult)returnValue;
            }
            // null值不能输出的问题 https://blog.csdn.net/a718515028/article/details/96474269
            writer.write(JSONObject.toJSONString(rr.toResultJson(), SerializerFeature.WriteNullStringAsEmpty));
            writer.flush();
        } catch (IOException ex) {
            throw new BusinessException("IO流错误！");
        }
    }

}
